import { defineStore } from 'pinia';
import axios from 'axios';

interface Trace {
  id: string;
  serviceId: string;
  serviceName: string;
  method: string;
  path: string;
  statusCode: number;
  duration: number;
  timestamp: string;
  request: {
    headers: Record<string, string>;
    body: any;
  };
  response: {
    headers: Record<string, string>;
    body: any;
  };
}

export const useTracesStore = defineStore('traces', {
  state: () => ({
    traces: [] as Trace[],
    loading: false,
    error: null as string | null,
    selectedTrace: null as Trace | null,
    filters: {
      service: '',
      statusCode: '',
      method: '',
      timeRange: '1h'
    }
  }),
  
  getters: {
    filteredTraces: (state) => {
      let filtered = [...state.traces];
      
      if (state.filters.service) {
        filtered = filtered.filter(trace => 
          trace.serviceId === state.filters.service || 
          trace.serviceName.includes(state.filters.service)
        );
      }
      
      if (state.filters.statusCode) {
        filtered = filtered.filter(trace => 
          trace.statusCode.toString().startsWith(state.filters.statusCode)
        );
      }
      
      if (state.filters.method) {
        filtered = filtered.filter(trace => 
          trace.method === state.filters.method
        );
      }
      
      // 时间范围过滤
      const now = new Date();
      let timeLimit = new Date();
      
      switch (state.filters.timeRange) {
        case '15m':
          timeLimit.setMinutes(now.getMinutes() - 15);
          break;
        case '1h':
          timeLimit.setHours(now.getHours() - 1);
          break;
        case '6h':
          timeLimit.setHours(now.getHours() - 6);
          break;
        case '24h':
          timeLimit.setHours(now.getHours() - 24);
          break;
        case '7d':
          timeLimit.setDate(now.getDate() - 7);
          break;
      }
      
      filtered = filtered.filter(trace => 
        new Date(trace.timestamp) >= timeLimit
      );
      
      return filtered;
    },
    
    traceCount: (state) => {
      return state.traces.length;
    },
    
    errorCount: (state) => {
      return state.traces.filter(trace => trace.statusCode >= 400).length;
    },
    
    avgResponseTime: (state) => {
      if (state.traces.length === 0) return 0;
      const sum = state.traces.reduce((acc, trace) => acc + trace.duration, 0);
      return sum / state.traces.length;
    }
  },
  
  actions: {
    async fetchTraces() {
      this.loading = true;
      this.error = null;
      
      try {
        // 替换为实际的API端点
        const response = await axios.get('/api/traces');
        this.traces = response.data;
      } catch (err: any) {
        this.error = err.message || '获取链路追踪数据失败';
        console.error('获取链路追踪数据失败:', err);
      } finally {
        this.loading = false;
      }
    },
    
    selectTrace(trace: Trace) {
      this.selectedTrace = trace;
    },
    
    clearSelectedTrace() {
      this.selectedTrace = null;
    },
    
    setFilter(key: string, value: string) {
      if (key in this.filters) {
        (this.filters as any)[key] = value;
      }
    },
    
    clearFilters() {
      this.filters = {
        service: '',
        statusCode: '',
        method: '',
        timeRange: '1h'
      };
    }
  }
});
